<!doctype html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no, width=device-width">
    <title>地理编码</title>
    <link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
    <style>
        html,
        body,
        #container {
            height: 100%;
            width: 100%;
        }

        .btn {
            width: 10rem;
            margin-left: 6.8rem;
        }
    </style>
    <style type="text/css">
        #panel {
            position: fixed;
            background-color: white;
            max-height: 90%;
            overflow-y: auto;
            top: 10px;
            right: 10px;
            width: 280px;
            z-index: 100;
        }

        #panel .amap-call {
            background-color: #009cf9;
            border-top-left-radius: 4px;
            border-top-right-radius: 4px;
        }

        #panel .amap-lib-driving {
            border-bottom-left-radius: 4px;
            border-bottom-right-radius: 4px;
            overflow: hidden;
        }
    </style>
</head>

<body>
    <div id="panel"></div>
    <div id="container"></div>
    <div class="input-card" style='width:28rem;'>
        <label style='color:grey'>地理编码，根据地址获取经纬度坐标</label>
        <div class="input-item">
            <div class="input-item-prepend"><span class="input-item-text">地址</span></div>
            <input id='address' type="text" value='北京市朝阳区阜荣街10号'>
        </div>
        <div class="input-item">
            <div class="input-item-prepend"><span class="input-item-text">经纬度</span></div>
            <input id='lnglat' disabled type="text">
        </div>
        <input id="geo" type="button" class="btn" value="地址 -> 经纬度" />
    </div>
    <script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
    <script
        src="https://webapi.amap.com/maps?v=1.4.15&key=2c16442f7b363740f75dcee72ca0a22c&plugin=AMap.Geocoder"></script>
    <!-- <script src="https://webapi.amap.com/maps?v=1.4.15&key=2c16442f7b363740f75dcee72ca0a22c&plugin=AMap.Driving"></script>
    <script src="https://webapi.amap.com/maps?v=1.4.15&key=2c16442f7b363740f75dcee72ca0a22c&plugin=AMap.DistrictSearch"></script> -->
    <script src="https://cache.amap.com/lbs/static/addToolbar.js"></script>

    <script type="text/javascript">

        var map = new AMap.Map("container", {
            resizeEnable: true,
            //crs: 'EPSG4326'
            enableHighAccuracy: true
        });

        var geocoder, marker;
        function geoCode() {
            var address = document.getElementById('address').value;
            const reg = /.+?(省|自治区|自治州|市|地区)/g
            let arr = address.match(reg)
            //if (!geocoder) {
            geocoder = null
            if (arr.length) {
                geocoder = new AMap.Geocoder({
                    city: arr[1], //城市设为北京，默认：“全国”
                });
            }
            //}

            let startPoint = {}
            let endPoint = {}
            let adcode = ''

            geocoder.getLocation(address, function (status, result) {
                if (status === 'complete' && result.geocodes.length) {
                    var lnglat = result.geocodes[0].location
                    console.log('geocoder.getLocation')
                    console.log(result)

                    startPoint.lng = lnglat.lng
                    startPoint.lat = lnglat.lat

                    geocoder.getAddress(lnglat, function (status, result) {
                        debugger
                        console.log('geocoder.getAddress')
                        console.log(result)

                        adcode = result.regeocode.addressComponent.adcode

                        if (status === 'complete' && result.regeocode) {

                            AMap.plugin('AMap.DistrictSearch', function () {
                                // 创建行政区查询对象
                                var district = new AMap.DistrictSearch({
                                    // 返回行政区边界坐标等具体信息
                                    extensions: 'all',
                                    // 设置查询行政区级别为 区 
                                    level: 'district'
                                })

                                district.search(adcode, function (status, result) {

                                    console.log('DistrictSearch')
                                    console.log(result)
                                    // 获取朝阳区的边界信息
                                    var bounds = result.districtList[0].boundaries
                                    var polygons = []
                                    if (bounds) {
                                        for (var i = 0, l = bounds.length; i < l; i++) {
                                            //生成行政区划polygon
                                            var polygon = new AMap.Polygon({
                                                map: map,
                                                strokeWeight: 1,
                                                path: bounds[i],
                                                fillOpacity: 0.7,
                                                fillColor: '#CCF3FF',
                                                strokeColor: '#CC66CC'
                                            })
                                            polygons.push(polygon)
                                        }
                                        // 地图自适应
                                        map.setFitView()
                                    }

                                    let center = result.districtList['0'].center

                                    endPoint.lng = center.lng
                                    endPoint.lat = center.lat

                                    AMap.plugin('AMap.Driving', function () {
                                        //构造路线导航类
                                        var driving = new AMap.Driving({
                                            map: map,
                                            panel: "panel"
                                        });
                                        console.log('起点是区域中心，终点是客户地址')
                                        // 根据起终点经纬度规划驾车导航路线
                                        driving.search(new AMap.LngLat(endPoint.lng, endPoint.lat), new AMap.LngLat(startPoint.lng, startPoint.lat), function (status, result) {
                                            // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
                                            if (status === 'complete') {
                                                log.success('绘制驾车路线完成')
                                            } else {
                                                log.error('获取驾车数据失败：' + result)
                                            }
                                        })
                                    })

                                })
                            })


                        } else {
                            log.error('根据经纬度查询地址失败')
                        }
                    });

                    document.getElementById('lnglat').value = lnglat;

                    if (!marker) {
                        marker = new AMap.Marker();
                        map.add(marker);
                    }
                    marker.setPosition(lnglat);
                    map.setFitView(marker);
                } else {
                    log.error('根据地址查询位置失败');
                }
            });
        }

        document.getElementById("geo").onclick = geoCode;
        document.getElementById('address').onkeydown = function (e) {
            if (e.keyCode === 13) {
                geoCode();
                return false;
            }
            return true;
        };
    </script>
</body>

</html>